# coding=utf-8
from flask_script import Manager
from flask_migrate import Migrate, MigrateCommand
from app import app
from exts import db
from utils.redis import Redis
from model import SeckillVoucher, Shop
from setting import Prefixs
from model import ShopType
from datetime import datetime
import json

manager = Manager(app)
Migrate(app, db, director="./migrations")
manager.add_command('db', MigrateCommand)


@manager.command
def SetShopTypeListCache():
    shop_types = ShopType.query.all()
    shop_type_list = [shop_type.to_dict() for shop_type in shop_types]
    # 封装数据，添加expire字段代表过期时间
    shop_type_result = {'data': shop_type_list, "expire": datetime.now().timestamp() + 3600 * 30}
    if Redis.set("shop_type_list", json.dumps(shop_type_result), expire=-1):  # 设置为永不过期
        print("添加缓存成功！")
        return
    print("添加缓存失败！")


@manager.command
def addSKVoucherCache():  # 批量添加秒杀券缓存
    voucher_list = SeckillVoucher.query.all()
    for skvoucher in voucher_list:
        Redis.hmset(Prefixs.seckill_voucher_stock_prefix + str(skvoucher.voucherID), skvoucher.to_dict())
    print("缓存添加成功！")


@manager.command
def delSKVoucherCache():  # 批量删除秒杀券缓存
    voucher_list = SeckillVoucher.query.all()
    for skvoucher in voucher_list:
        Redis.delete(Prefixs.seckill_voucher_stock_prefix + str(skvoucher.voucherID))
    print("缓存删除成功！")

# 添加商店地理位置缓存
@manager.command
def addShopGeoToRedis():
    groups = dict()
    shops_info = Shop.query.all()
    for shop in shops_info:
        # 如果typeid没有就创建一个空列表并添加商店信息
        if shop.type_id not in groups:
            groups[shop.type_id] = [shop.to_dict()]
        # 如果typeid已经存在就之间添加商店信息
        else:
            groups[shop.type_id].append(shop.to_dict())
    for typeid in groups:
        key = Prefixs.shop_geo + str(typeid)
        value = []
        # 拿到同一type的所有商店信息
        for shop in groups[typeid]:
            value += [shop['x'], shop['y'], shop['id']]
        Redis.geoadd(key, value)
    print(value)
    print("商店地理位置缓存添加成功！")

if __name__ == '__main__':
    manager.run()
